package models;

import java.util.Date;
import java.util.List;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;

import play.db.ebean.Model;

@Entity
@Table(name = "orders")
public class Order extends Model {

	/**
	 * 
	 */
	private static final long serialVersionUID = 4536574098116695794L;

	public static Finder<Long, Order> find = new Finder<Long, Order>(
			Long.class, Order.class);

	@Id
	private Long id;

	@ManyToOne(fetch = FetchType.EAGER)
	@JoinColumn(name = "user_id")
	private User user;

	@OneToMany(fetch = FetchType.LAZY, cascade = { CascadeType.ALL,
			CascadeType.PERSIST, CascadeType.REMOVE })
	@JoinColumn(name = "order_id")
	private Set<OrderItem> orderItems;

	@NotNull
	private Date date;

	public static List<Order> ordersByUser(User u) {
		return find.where().eq("user_id", u.getId()).orderBy("date DESC")
				.findList();
	}

	public void addToOrderItems(OrderItem oi) {
		orderItems.add(oi);
	}

	public static void create(Order o) {
		o.save();
	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public Set<OrderItem> getOrderItems() {
		return orderItems;
	}

	public void setOrderItems(Set<OrderItem> orderItems) {
		this.orderItems = orderItems;
	}

	public Date getDate() {
		return date;
	}

	public void setDate(Date date) {
		this.date = date;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = super.hashCode();
		result = prime * result
				+ ((getDate() == null) ? 0 : getDate().hashCode());
		result = prime * result
				+ ((getUser() == null) ? 0 : getUser().hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj) {
			return true;
		}
		if (!super.equals(obj)) {
			return false;
		}
		if (getClass() != obj.getClass()) {
			return false;
		}
		Order other = (Order) obj;
		if (getDate() == null) {
			if (other.getDate() != null) {
				return false;
			}
		} else if (!getDate().equals(other.getDate())) {
			return false;
		}
		if (getUser() == null) {
			if (other.getUser() != null) {
				return false;
			}
		} else if (!getUser().equals(other.getUser())) {
			return false;
		}
		return true;
	}

}

/*
 * With the Scala API, you can do it like this to get a java.io.File to the app:
 * import play.api.Play.current Play.application.path In Java: * import play.*;
 * Play.application().path();
 */